package cn.iocoder.yudao.module.scrm.controller.admin.schedules;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.CustomerController;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.CustomerRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.schedules.vo.SchedulesCustomerPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.schedules.vo.SchedulesCustomerRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.schedules.vo.SchedulesCustomerUpdateReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.schedules.vo.SchedulesPageReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.schedulescustomer.SchedulesCustomerDO;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.service.schedules.SchedulesCustomerService;
import cn.iocoder.yudao.module.scrm.service.schedules.SchedulesService;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;


@Tag(name = "管理后台 - 排期客户")
@RestController
@RequestMapping("/scrm/schedules-customer")
@Validated
public class SchedulesCustomerController {

    @Resource
    private SchedulesCustomerService schedulesCustomerService;

    @Resource
    private CustomerController customerController;

    @Resource
    private CustomerService customerService;

    @Resource
    private PermissionApi permissionApi;

    @Resource
    private SchedulesService schedulesService;

    @PutMapping("/update")
    @Operation(summary = "更新排期客户")
    @PermitAll
    public CommonResult<Boolean> updateSchedulesCustomer(@Valid @RequestBody SchedulesCustomerUpdateReqVO updateReqVO) {
        schedulesCustomerService.updateSchedulesCustomer(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除排期客户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:schedules-customer:delete')")
    public CommonResult<Boolean> deleteSchedulesCustomer(@RequestParam("id") Long id) {
        schedulesCustomerService.deleteSchedulesCustomer(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得排期客户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:schedules-customer:query')")
    public CommonResult<SchedulesCustomerRespVO> getSchedulesCustomer(@RequestParam("id") Long id) {
        SchedulesCustomerDO schedulesCustomer = schedulesCustomerService.getSchedulesCustomer(id);
        return success(BeanUtils.toBean(schedulesCustomer, SchedulesCustomerRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得排期客户分页")
    @PreAuthorize("@ss.hasPermission('scrm:schedules-customer:query')")
    public CommonResult<PageResult<CustomerRespVO>> getSchedulesCustomerPage(@Valid SchedulesCustomerPageReqVO pageReqVO) {
        PageResult<SchedulesCustomerDO> pageResult = schedulesCustomerService.getSchedulesCustomerPage(pageReqVO);
        List<CustomerDO> list = customerService.getCustomerList(pageResult.getList().stream().map(SchedulesCustomerDO::getCustomerId).collect(Collectors.toList()));
        // 2. 拼接数据
        return success(new PageResult<>(customerController.buildCustomerDetailList(list), pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出排期客户 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:schedules-customer:export')")
    @OperateLog(type = EXPORT)
    public void exportSchedulesCustomerExcel(@Valid SchedulesCustomerPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        //不是超级管理员只能导出自己的
        Long loginUserId = getLoginUserId();
        if (!permissionApi.roleIsSuperAdmin(loginUserId).getCheckedData()){
            pageReqVO.setCreator(Objects.requireNonNull(loginUserId).toString());
        }
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);

        IPage<CustomerDO> page = schedulesService.getCustomerList(new SchedulesPageReqVO().setId(pageReqVO.getSchedulesId()));

        // 2. 拼接数据
        List<CustomerRespVO> customerRespVOS = customerController.buildCustomerDetailList(page.getRecords());
        List<SchedulesCustomerRespVO> bean = BeanUtils.toBean(customerRespVOS, SchedulesCustomerRespVO.class);
        for (SchedulesCustomerRespVO item : bean) {
            // 假设你的字段是 `numberField`
           if (item.getStatus()==0){
               item.setStatusShow("未签到");
           }else if (item.getStatus()==1){
                item.setStatusShow("已签到");
           }
        }
        // 导出 Excel
        ExcelUtils.write(response, "排期客户.xls", "数据", SchedulesCustomerRespVO.class,
                        BeanUtils.toBean(bean, SchedulesCustomerRespVO.class));
    }

}